/*
 *  input.cpp
 *  Sinnca Engine Demo
 *
 *  Created by Ryan Oldis on 1/18/11.
 *  Copyright 2011 Sinnca Studios. All rights reserved.
 *
 */

#include "input.h"

#include "script.h"


Input* Input::_instance = NULL;

Input* Input::Instance()
{
	if (_instance == NULL)
	{
		_instance = new Input();
	}
	
	return _instance;
}

Input::Input()
{
	
	for (int i = 0; i < 322; i++)
	{
		keyList[i] = 0;
	}
	
	// setup keyboard
	listKeys();
	
}


bool Input::Update()
{
	while (SDL_PollEvent(&event))
	{
		switch (event.type)
		{
			case SDL_QUIT:
				return true;
				break;
				
			case SDL_KEYDOWN:
				keyList[event.key.keysym.sym] = 1;
				break;
				
			case SDL_KEYUP:
				keyList[event.key.keysym.sym] = 0;
				break;
				
			case SDL_MOUSEMOTION:
				m_x = event.motion.x;
				m_y = event.motion.y;
				break;
			
			case SDL_MOUSEBUTTONDOWN:
				if (event.button.button == SDL_BUTTON_LEFT)
				{
					leftClk = 1;
					printf("mouse: %d, %d ", m_x, m_y);
				}
				
				if (event.button.button == SDL_BUTTON_MIDDLE)
				{
					midClk = 1;
				}
				
				if (event.button.button == SDL_BUTTON_RIGHT)
				{
					rightClk = 1;
				}
				break;
				
			case SDL_MOUSEBUTTONUP:
				if (event.button.button == SDL_BUTTON_LEFT)
				{
					leftClk = 0;
				}
				
				if (event.button.button == SDL_BUTTON_MIDDLE)
				{
					midClk = 0;
				}
				
				if (event.button.button == SDL_BUTTON_RIGHT)
				{
					rightClk = 0;
				}
				break;
				
			case SDL_JOYAXISMOTION:
				
				if( ( event.jaxis.value > -8000 ) && ( event.jaxis.value < 8000 ) )
                {
                    pad.axies[event.jaxis.axis] = 0.0;
                } else {
					pad.axies[event.jaxis.axis] = (event.jaxis.value / 1000.f) / 3.1;
				}
				
				
			case SDL_JOYBUTTONDOWN:
				
				pad.buttons[event.jbutton.button] = 1;
				
				break;

			case SDL_JOYBUTTONUP:
				
				pad.buttons[event.jbutton.button] = 0;
				
				break;


			default:
				break;
		}
	}
	
	/*
	for (int i = 0; i < 322; i++)
	{
		if (keyList[i] == 1)
		{
			keyList[i] = 2;	// key is now held
		}
	}
	*/
	
	return false;
}


int l_keyDown(lua_State* L)
{
	
	int i = lua_tointeger(L, -1);
	
	lua_pushinteger(L, input->keyList[i]);
	
	
	return 1;
}

int l_getMouseCo(lua_State* L)
{
	lua_pushinteger(L, input->m_x);
	lua_pushinteger(L, input->m_y);
	
	return 2;
}


